package com.xuanrui.wxCommons.handler;


import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.util.WxMpConfigStorageHolder;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class UnsubscribeHandler extends AbstractHandler {
//    @Resource(name = "userInfoService")
//    private IUserInfoService userInfoService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        String openId = wxMessage.getFromUser();
        String apppId = WxMpConfigStorageHolder.get();
        this.logger.info("取消关注用户 OPENID: " + openId);
        // TODO 可以更新本地数据库为取消关注状态

        // 获取微信用户基本信息
        try {
            this.logger.info("{}", wxMpService.getUserService().userInfo(openId));
            WxMpUser userWxInfo = wxMpService.getUserService().userInfo(openId);
//            this.logger.info(userWxInfo.toString());
            this.logger.info("unionId:" + userWxInfo.getUnionId());
            String unionId = userWxInfo.getUnionId();
            if (userWxInfo != null) {
//                UserInfoExt userExt = userInfoService.getDetailBySearch(UserInfoSearchExt.getInstance().setDelFlagEq(WhetherEnum.NO.getValue()).setUnionIdEq(unionId));
//                //用户不存在  创建用户、个人信息 以及 企业HR记录
//                if (StringUtil.isNotObjEmpty(userExt)) {
//                    try {
//                        userInfoService.update((UserInfoExt) userExt.setMpOpenId(null));
//                    } catch (Exception e) {
//
//                    }
//                    return null;
//
//
//                }
            }
        } catch (WxErrorException e) {
            this.logger.info("{}", e);
            if (e.getError().getErrorCode() == 48001) {
                this.logger.info("该公众号没有获取用户信息权限！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.logger.info(e.getMessage());
        }
        return null;
    }

}
